#!/usr/bin/python

import sqlite3
# 样例：4361106750091296769
import requests
from elasticsearch import Elasticsearch
import snowflake.client
from elasticsearch.helpers import bulk
def get_snowflake_uuid():
    guid = snowflake.client.get_guid()
    return guid
print("-----------分布式id服务-----------")
print(get_snowflake_uuid())
print("-------------------------")
conn = sqlite3.connect('D:\\flask\\flash-cards-remember\computer-science-flash-cards\db\cards.db')
print ("Opened database successfully");
cursor = conn.execute("SELECT *  from cards")
REQUEST_ES_IP_PORT = '39.106.226.131:9200'
obj = Elasticsearch(REQUEST_ES_IP_PORT)
# 查询所有数据、把 查询到的数据发送到elasticsearch中，id、生成eid放入到数据库中。
for row in cursor:
   #  mysql id 传入 和elasticsearch作为新值插入相应索引
   print ("ID = ", row[0],"\n")
   # eid 生成 需要更新到sqlite中
   eid = get_snowflake_uuid()
   # print ("front = ", row[2])
   # print ("back = ", row[3])
   # print ("time = ", row[6], "\n")

   rowdata = {
       "createtime":row[6],
       "sqlId":row[0],
       "front":row[2],
       "back":row[3]
   }
   back =row[3]
   if(back == "back" or back=="                        "or back=="                        "or back==""):
       back = row[5]
   result = obj.index(index='users', doc_type='_doc',id=eid, body=rowdata)
   # result = bulk(obj, actions=[rowdata])
   conn.execute("UPDATE cards set eid = ?,back=? where id=?",[eid,back,row[0]])
   conn.commit()
# 发送拼接好的所有json数据到elasticsearch中索引。（）
# 得到elasticsearch返回的id之后，更新相应的eid字段。（用于更新数据等）
conn.close()